#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include "send_to_server.h"

extern int skt_fd;

void set_client_data(ClientData *cdata, GameCmd cmd, SnakeDir dir)
{
    cdata->cmd = cmd;
    cdata->dir = dir;
}


//static SnakeDir parse_pc_input_dir(const char c);
//static SnakeDir parse_pc_input_cmd(const char c);
static void parse_pc_input(SnakeDir *dir, GameCmd *cmd, const char c);

/*
*@func:发送数据线程，阻塞读按键，当按键有值的时候，向服务器发送数据
*@desc:通过套接字通信（sock
*/
void *send_data(void *arg)
{
    while(1)
    {
        //1. 读取按键的值（阻塞读取）
        #if 0
        char buf;
        int key_fd;
        read(key_fd, buf, sizeof(buf));
        #endif
        
        #if 0 //从PC上读取按键值
            char c = 0;
            read(STDIN_FILENO, &c, sizeof(c));
        #endif
        char c = getchar();
        getchar(); //清除回车符

        //SnakeDir dir = parse_pc_input_dir(c);
        GameCmd cmd = NONE_CMD;
        SnakeDir dir = NONE_DIR;

        parse_pc_input(&dir, &cmd,c);
        printf("We get a char:%c\n", c);
        
        //2. 当读到值之后，解析这个值，设置ClientData，然后向服务器发送数据
        ClientData cdata;
        //此处应该根据读到的按键值，设置GameCmd和SnakeDir
        //set_client_data(&cdata, NONE_CMD, NONE_DIR);
        set_client_data(&cdata, cmd, dir);
        send(skt_fd, &cdata, sizeof(cdata), 0);
    }
}



/*
*func:从PC上获取输入，以取得SnakeDir+GameCmd，为后面构成ClientData做准备（代替触摸屏测试）
*/
static void parse_pc_input(SnakeDir *dir, GameCmd *cmd, const char c)
{
    //SnakeDir dir = NONE_DIR;

    switch (c)
    {
    case 'A':
    case 'a':
        *dir = LEFT;
        break;
    case 'W':
    case 'w':
        *dir = UP;
        break;

    case 'S':
    case 's':
        *dir = DOWN;
        break;
    
    case 'D':
    case 'd':
        *dir = RIGHT;
        break;

    case 'g':
    case 'G':
    case '>':
        *cmd = START_GAME;
        break;
    case 'E':
    case 'e':
    case '<':
    case 'x':
        *cmd = EXIT_GAME;
        break;
    
    
    default:
        *dir = NONE_DIR;
        *cmd = NONE_CMD;
        break;
    }
    //return dir;
}
